import { message } from 'antd';
import { BaseResponse } from '@/types/services';
import { NavigateFunction } from 'react-router-dom';
let nav: NavigateFunction | null = null;
export const setNav = (n: NavigateFunction) => {
  nav = n;
};
class Exception extends Error {
  statusCode: number;
  constructor(message: string, statusCode: number) {
    super(typeof message === 'string' ? message : message[0]);
    this.name = 'Exception';
    this.statusCode = statusCode;
  }
}

const verifyRes = <T>(res: BaseResponse<T>) => {
  if (!res.success) {
    throw new Exception(res.message, res.statusCode);
  }
};

const catchErr = (err: Error) => {
  if (err instanceof Exception) {
    console.error(err);
    message.error(
      typeof err.message === 'string' ? err.message : err.message[0]
    );
  }
  // if (err instanceof Exception && err.statusCode === 401) {
  //   location.href = `/api/v1/user/oauth2?cb=${encodeURIComponent(
  //     location.href
  //   )}`;
  // }

  if (err instanceof Exception && err.statusCode == 401) {
    if (nav) {
      nav('/login');
    }
  }
};
export { Exception, verifyRes, catchErr };
